package org.jeecg.modules.tt_question_collect.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import kong.unirest.HttpResponse;
import kong.unirest.JsonNode;
import kong.unirest.Unirest;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.CommonSendStatus;
import org.jeecg.common.constant.WebsocketConst;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.message.entity.SysMessage;
import org.jeecg.modules.message.service.ISysMessageService;
import org.jeecg.modules.message.websocket.WebSocket;
import org.jeecg.modules.system.entity.SysAnnouncement;
import org.jeecg.modules.system.service.ISysAnnouncementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 消息推送中心
 *
 * @Title: MsgPushController
 * @ProjectName jeecg
 * @Description: TODO
 * @Author Admin
 * @Date 2021/3/116:13
 */
@Slf4j
@Api(tags = "消息推送")
@RestController
@RequestMapping("/request/msg/push")
public class MsgPushController {

    public static final String PREFIX_USER_TOKEN = "prefix_qwx_token";

    public static final long EXPIRE_TIME = 2 * 60 * 60 * 1000;

    @Autowired
    private ISysAnnouncementService sysAnnouncementService;

    @Autowired
    private ISysMessageService sysMessageService;

    @Resource
    private WebSocket webSocket;

    @Autowired
    private RedisUtil redisUtil;

    public static String CORPID;

    public static String CORPSECRET;

    public static String AGENTID;

    @Value("${justauth.type.WECHAT_ENTERPRISE.client-id}")
    public void setCorpId(String corpId) {
        CORPID = corpId;
    }

    @Value("${justauth.type.WECHAT_ENTERPRISE.client-secret}")
    public void setCorpSecret(String corpSecret) {
        CORPSECRET = corpSecret;
    }

    @Value("${justauth.type.WECHAT_ENTERPRISE.agent-id}")
    public void setAgentId(String agentId) {
        AGENTID = agentId;
    }

    /**
     * 系统消息定点推送
     *
     * @param toUsers     以英文,分隔
     * @param title
     * @param msgAbstract
     * @param content
     * @return
     */
    @AutoLog(value = "消息推送-系统消息定点")
    @ApiOperation(value = "消息推送-系统消息定点", notes = "消息推送-系统消息定点")
    @PostMapping(value = "/{msgType}")
    public Result<SysAnnouncement> msgPushUserId(@PathVariable("msgType") String msgType, @PathVariable("toUsers") String toUsers, String title, String msgAbstract, String content) {
        Result<SysAnnouncement> result = new Result<>();
        if ("1".equals(msgType)) { // 系统消息
            SysAnnouncement sysAnnouncement = new SysAnnouncement();

            sysAnnouncement.setTitile(title);
            sysAnnouncement.setUserIds(toUsers);
            sysAnnouncement.setMsgType(CommonConstant.MSG_TYPE_UESR);
            sysAnnouncement.setMsgCategory(CommonConstant.MSG_CATEGORY_2);
            sysAnnouncement.setMsgAbstract(msgAbstract);
            sysAnnouncement.setMsgContent(content);
            sysAnnouncement.setPriority(CommonConstant.PRIORITY_M);

            sysAnnouncement.setCreateBy("AdminSys");
            sysAnnouncement.setSender("系统运营团队");
            sysAnnouncement.setSendTime(new Date());
            sysAnnouncement.setCreateTime(new Date());
            sysAnnouncement.setStartTime(new Date());
            sysAnnouncement.setEndTime(new Date());

            sysAnnouncement.setDelFlag(CommonConstant.DEL_FLAG_0.toString());
            sysAnnouncement.setSendStatus(CommonSendStatus.PUBLISHED_STATUS_1);//已发布

            try {
                sysAnnouncementService.saveAnnouncement(sysAnnouncement);
                result.setResult(sysAnnouncement);
            }
            catch (Exception e) {
                e.printStackTrace();
                return result.error500("发送失败！");
            }
        }
        else if ("2".equals(msgType)) { // 企业微信
            String accessToken = saveToken();
            SysMessage sysMessage = new SysMessage();

            sysMessage.setEsTitle(title);
            sysMessage.setEsType("5");
            sysMessage.setEsReceiver(toUsers);
            sysMessage.setEsContent(content);
            sysMessage.setEsSendStatus("0"); // 未推送
            sysMessage.setEsSendNum(20);
            sysMessage.setCreateBy("AdminSys");
            sysMessage.setCreateTime(new Date());

            JSONObject requestBody = getRequestBody(toUsers, content);
            HttpResponse<JsonNode> response = httpKitPostJson(accessToken, requestBody);
            if (200 == response.getStatus()) {
                sysMessage.setEsSendTime(new Date());
                JSONObject jsonObject = JSONObject.parseObject(response.getBody().toString());
                log.info("企业微信推送消息-文本信息--->" + JSON.toJSONString(jsonObject));
                if ("0".equals(jsonObject.getString("errcode"))) {
                    sysMessage.setEsSendStatus("1"); // 推送成功
                }
                else {
                    sysMessage.setEsSendStatus("2"); // 推送失败
                    sysMessage.setEsResult(JSON.toJSONString(jsonObject));
                }
                sysMessage.setRemark(JSON.toJSONString(jsonObject));
            }
            sysMessageService.save(sysMessage);
        }
        return result;
    }

    public void msgSysPush(SysAnnouncement sysAnnouncement) {
        String userId = sysAnnouncement.getUserIds();
        String[] userIds = userId.substring(0, (userId.length() - 1)).split(",");
        JSONObject obj = new JSONObject();
        obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER);
        obj.put(WebsocketConst.MSG_ID, sysAnnouncement.getId());
        obj.put(WebsocketConst.MSG_TXT, sysAnnouncement.getTitile());
        log.info("系统推送消息-文本信息--->" + JSON.toJSONString(obj));
        webSocket.sendMoreMessage(userIds, obj.toJSONString());
    }

    private JSONObject getRequestBody(String toUsers, String content) {
        JSONObject requestBody = new JSONObject();
        String[] userIds = toUsers.substring(0, (toUsers.length() - 1)).split(",");
        String toUser = "";
        for (String userId : userIds) {
            toUser += userId + "|";
        }
        toUser = toUser.substring(0, (toUsers.length() - 1));
        requestBody.put("touser", toUser);
        requestBody.put("toparty", "");
        requestBody.put("totag", "");
        requestBody.put("msgtype", "text");
        requestBody.put("agentid", AGENTID);
        JSONObject text = new JSONObject();
        text.put("content", content);
        requestBody.put("text", text);
        //requestBody.put("safe", 1);
        return requestBody;
    }

    private String saveToken() {
        String accessToken = String.valueOf(redisUtil.get(PREFIX_USER_TOKEN));
        if (!oConvertUtils.isNotEmpty(accessToken)) {
            HttpResponse<JsonNode> response = httpKitGetJson();
            if (200 == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.getBody().toString());
                log.info("企业微信推送消息获取Token--->" + JSON.toJSONString(jsonObject));
                if ("0".equals(jsonObject.getString("errcode"))) {
                    accessToken = jsonObject.getString("access_token");
                    redisUtil.set(PREFIX_USER_TOKEN, accessToken);
                    // 设置超时时间
                    redisUtil.expire(PREFIX_USER_TOKEN, EXPIRE_TIME / 1000);
                }
            }
        }
        log.info("企业微信推送消息获取Token--->" + accessToken);
        return accessToken;
    }

    private HttpResponse<JsonNode> httpKitGetJson() {
        HttpResponse<JsonNode> response = Unirest.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken")
                                                 .header("Accept", "application/json")
                                                 .queryString("corpid", CORPID)
                                                 .queryString("corpsecret", CORPSECRET)
                                                 .asJson();
        return response;
    }

    private HttpResponse<JsonNode> httpKitPostJson(String accessToken, JSONObject requestBody) {
        HttpResponse<JsonNode> response = Unirest.post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken)
                                                 .header("Accept", "application/json")
                                                 .header("Accept", "application/json")
                                                 .header("Content-Type", "application/json")
                                                 .body(requestBody)
                                                 .asJson();
        return response;
    }

}
